package pri.hillchen.springbootstd.sso.common.util;

import java.text.ParseException;
import java.util.Random;

/**
 * Created by hillchen on 2017/10/18 0018.
 */
public class IdWorker {
    private Random random = new Random();
    private int maxRandomNum = 100;
    private final static int SUM_BITS = 64;
    /**
     * 起始时间戳
     */
    private final static long TWEPOCH = 1288834974657L;
    /**
     * id生成器编号所占位数
     */
    private final static int WORKER_ID_BITS = 4;
    public final static int MAX_WORKER_ID = -1 ^ -1 << WORKER_ID_BITS;


    /**
     * 相对时间戳所占位数
     */
    private final static int TIMESTAMP_LEFT_BITS = 42;
    /**
     * 毫秒内编号位数
     */
    private final static int SEQUENCE_BITS = SUM_BITS - WORKER_ID_BITS - TIMESTAMP_LEFT_BITS;
    /**
     * id生成器编号偏移量
     */
    private final static int WORKER_ID_SHIFT = SEQUENCE_BITS;
    /**
     *相对时间戳偏移量
     */
    private final static int TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS  + WORKER_ID_BITS;
    /**
     * 毫秒内最大编号
     */
    public final static int SEQUENCE_MASK = -1 ^ -1 << SEQUENCE_BITS;

    private final int workerId;
    private long sequence = 0L;

    private long lastTimestamp = -1L;

    private static IdWorker idWorker;
    public static void initIdWorker(final int workerId){
        if(idWorker !=  null){
            if(workerId == idWorker.workerId){
                throw new RuntimeException("IdWorker has  init , but workerId not eq!");
            }
        }else{
            idWorker = new IdWorker(workerId);
        }

    }
    public static IdWorker getInstance(){
        if(idWorker == null){
            throw new RuntimeException("IdWorker has not init !");
        }
        return idWorker;
    }

    private IdWorker(final int workerId) {
        super();
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException(String.format(
                    "worker Id can't be greater than %d or less than 0",
                    MAX_WORKER_ID));
        }
        this.workerId = workerId;
    }

    public synchronized long nextId() {
        long timestamp = this.timeGen();
        if (this.lastTimestamp == timestamp) {
            this.sequence = (this.sequence + 1) & SEQUENCE_MASK;
            if (this.sequence == 0) {
                System.out.println("###########" + SEQUENCE_MASK);
                timestamp = this.tilNextMillis(this.lastTimestamp);
            }
        } else {

            this.sequence = random.nextInt(maxRandomNum);
        }
        if (timestamp < this.lastTimestamp) {
            try {
                throw new Exception(
                        String.format(
                                "Clock moved backwards.  Refusing to generate id for %d milliseconds",
                                this.lastTimestamp - timestamp));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        this.lastTimestamp = timestamp;
        long nextId = (this.workerId << WORKER_ID_SHIFT) |((timestamp - TWEPOCH << TIMESTAMP_LEFT_SHIFT))
                |  (this.sequence);
        System.out.println("timestamp:" + timestamp + ",timestampLeftShift:"
                + TIMESTAMP_LEFT_SHIFT + ",nextId:" + nextId + ",workerId:"
                + workerId + ",sequence:" + sequence);
        return nextId;
    }

    private long tilNextMillis(final long lastTimestamp) {
        long timestamp = this.timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = this.timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }


    public static void main(String[] args) throws ParseException {
        IdWorker worker2 = new IdWorker(10);
        int forEnd = 10;
        for(int i=0;i<forEnd;i++){
            System.out.println(worker2.nextId());
        }
    }
}
